import "./WebPanel.scss";
import { useSelector, useDispatch } from "react-redux";
import { v4 as uuidv4 } from "uuid";
import ZDnd from "@/plugins/dnd/dnd";
import DynamicComponentLoader from "@/components/Editor/components/DynamicComponentLoader";
import Dnd from "@/components/Editor/Dnd";

function WebPanel() {
  const dispatch = useDispatch();
  const {
    editorConfig: {
      webConfig,
      global: {
        scale,
        ruleWidth,
        scaleContainerMargin,
        sliderWidth,
        topNavHeight,
      },
    },
    webRenderData: { components },
  } = useSelector((state) => (state as any).editor);

  const [webPanelStyle, setWebPanelStyle] = useState(webConfig);
  const webPanel = useRef<HTMLDivElement | null>(null);
  const webDndPanel = useRef<HTMLDivElement | null>(null);
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });
  const [DndComponent, setDndComponent] = useState<React.ComponentType | null>(
    null
  );




 

  const handleDrop = useCallback(async (e: React.DragEvent<HTMLDivElement>) => {
    let data = e.dataTransfer.getData("dragData");
    if (data) {
      let dndData = JSON.parse(data);
      console.log("拖拽结束组件数据", dndData);

      const { x, y } = getXY(e);
      const uuid = uuidv4();
      // redux新增组件
      dispatch({
        type: "editor/addComponent",
        payload: {
          id: uuid,
          zIndex: components.length,
          x,
          y,
          ...dndData,
        },
      });
      setDragPosition({ x, y });
    } else {
      console.log("暂无拖拽组件数据");
    }
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  }, []);

  // 获取拖拽位置
  const getXY = (e: React.MouseEvent | React.DragEvent) => {
    const x = e.clientX - sliderWidth - ruleWidth - scaleContainerMargin;
    const y = e.clientY - topNavHeight - ruleWidth - scaleContainerMargin;
    return { x, y };
  };

  return (
    <div
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      ref={webPanel}
      className="lego-editor-container-panel"
      style={webPanelStyle}
    >
      <Dnd scale={scale} children={
        components.map((item: any) => (
          <div
          className="lego-editor-container-panel-component-item"
          key={item.id}
          style={{ position: "absolute", left: item.x, top: item.y }}
        >
          <DynamicComponentLoader config={item} />
        </div>
        ))
      }>

      </Dnd>
      {/* 循环多个组件
      {components.map((item: any) => (
        <div
          className="lego-editor-container-panel-component-item"
          key={item.id}
          style={{ position: "absolute", left: item.x, top: item.y }}
        >
          <DynamicComponentLoader config={item} />
        </div>
      ))} */}
    </div>
  );
}

export default WebPanel;
